//
//  PKHomeViewModal.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/22.
//

import UIKit
import RxSwift
import RxCocoa
import RxOptional
enum Mode{
    case text
    case image
}
enum InputMode {
    case text(String)
    case image(Data)
}

class PKHomeViewModal :PKBaseViewModal ,viewModalType{
    
    

   
//    let pollingControl = PollingController<PKTaskResponseModal>()
   private let disposeBag = DisposeBag()
   
//   private let service : APIService
    let inputTextRelay = BehaviorRelay<String>(value: "")
   let uploadImageRelay = BehaviorRelay<UIImage?>(value: nil)
   let selectSegmentRelay = BehaviorRelay<Mode>(value: .text)
   let resultImageTapped = PublishRelay<Void>()
   let generateTapped  = PublishRelay<Void>()
   let menuTapped = PublishRelay<Void>()
   let GoitTapped = PublishRelay<Void>()
  
    let polling = PKPollingController<PKTaskResponseModal>()

    let isLoding = BehaviorRelay<Bool>(value: false)
//    let ImageResult : Observable<UIImage>
    struct Input {
    //    let textToImageResult : Observable<UIImage>
  
       let showEmptyTextAlert : Observable<Bool>
       let showEmptyImageAlert : Observable<Bool>
       let shouldTriggerTextGenerate : Observable<String>
       let shouldTriggerImageGenerate : Observable<String>
    
        let textInput : Observable<String>
        let selectedImage : Observable<UIImage?>
        let selectedMode : Observable<Mode>
    }
    private let _resultImage = BehaviorRelay<UIImage?>(value: nil)
        private let _errorMessage = PublishRelay<String>()
        private let _isLoading = BehaviorRelay<Bool>(value: false)
    struct Output{
        
    }
    
    func transform(input: Input) -> Output {
        
//        generateTapped.do { <#Void#> in
//            <#code#>
//        }
        
        
        
        
        
        
        
        
        
        
        
        
        
//        input.inputTextRelay
        return Output()
    }

}

private extension PKHomeViewModal {
    func prepareGenerationMode(text: String, image: UIImage?, mode: Mode) -> Observable<InputMode> {
          switch mode {
          case .text:
              let clean = text.trimmingCharacters(in: .whitespacesAndNewlines)
              if clean.isEmpty {
                  _errorMessage.accept("Please enter the description text.")
                  return .empty()
              } else if clean.count < 10 {
                  _errorMessage.accept("Please provide a more detailed text.")
                  return .empty()
              }
              return .just(.text(clean))
              
          case .image:
              guard let image = image else {
                  _errorMessage.accept("请Please upload an image.")
                  return .empty()
              }
              guard let data = image.jpegData(compressionQuality: 0.9) else {
                  _errorMessage.accept("图片格式错误")
                  return .empty()
              }
              return .just(.image(data))
          }
      }
    func submitGenerationRequest(mode: InputMode) -> Observable<String> {
        switch mode {
        case .text:
               // 此处直接返回 taskURL
            NetworkManager.shared.requestAuthObject(.uploadImage(image: UIImage(), description: "", color_type: "2", size: "1:1", img_type: "1"), type: PKTaskModal.self, using: NetworkManager.shared.authprovider)
                .map({ modal in
                    return modal.task_id ?? ""
                })
                .asObservable()
            
        case .image:
            NetworkManager.shared.requestAuthObject(.uploadImage(image: UIImage(), description: "", color_type: "2", size: "1:1", img_type: "1"), type: PKTaskModal.self, using: NetworkManager.shared.authprovider)
                .map({ modal in
                    return modal.task_id ?? ""
                })
                .asObservable()
            
        }

    }
//    func pollForImageURL(taskURL: String) -> Observable<String> {
////        polling.start(pollInterval: .seconds(2)) {
////            NetworkManager.shared.requestAuthObject(.tasks(taskId: self.taskID ?? ""), type: PKTaskResponseModal.self,using: NetworkManager.shared.authprovider)
//        }
//        
    
    
    func downloadImage(from url: String) -> Observable<UIImage?> {
           guard let u = URL(string: url) else { return .just(nil) }
           return URLSession.shared.rx
               .data(request: URLRequest(url: u))
               .map { UIImage(data: $0) }
       }
}
